package com.cowin.base;


import com.cowin.base.annotation.AutoCreateDate;
import com.cowin.base.annotation.AutoUpdateDate;
import com.cowin.utils.ClazzUtils;
import com.google.common.base.Preconditions;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Condition;

import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * Copyright (C), 1998-2018, 奇瑞信息
 *
 * @author : 于超
 * @Date: 2019/8/29 17:25
 * @Description:
 */
public abstract class AbstractServiceImpl<T> implements Service<T> {
    @Autowired
    protected Mapper<T> mapper;

    private Class<T> modelClass;

    public AbstractServiceImpl() {
        ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
        modelClass = (Class<T>) pt.getActualTypeArguments()[0];
    }

    @Override
    public int save(T model) {
        Preconditions.checkArgument(model != null);
        ClazzUtils.injectDate(model, AutoCreateDate.class);
        return mapper.insertSelective(model);
    }


    @Override
    public int deleteById(Integer id) {
        return mapper.deleteByPrimaryKey(id);
    }


    @Override
    public int update(T model) {
        Preconditions.checkArgument(model != null);
        ClazzUtils.injectDate(model, AutoUpdateDate.class);
        return mapper.updateByPrimaryKeySelective(model);
    }

    @Override
    public T findById(Integer id) {
        return mapper.selectByPrimaryKey(id);
    }


    @Override
    public List<T> findByCondition(Condition condition) {
        return mapper.selectByCondition(condition);
    }

    @Override
    public List<T> findAll() {
        return mapper.selectAll();
    }

    @Override
    public int deleterByCondition(Condition condition) {
        return mapper.deleteByCondition(condition);
    }

}

